<template>
  <el-dialog
    title="常规任务"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="96%"
    height="88%"
    v-dialog-drag
    class="work-abnormal-dialog"
    :close-on-click-modal="false"
    top="3vh"
    @close="dialogClose()"
    @open="dialogOpen()"
  >
    <div class="box-card">
      <el-form ref="queryForm" :inline="true"  class="clearfix"  @submit.native.prevent>
        <el-form-item
          prop="erpCommonList"
        >
          <el-cascader
            v-model="erpCommonList"
            :options="treeList"
            :props='defaultProps'
            clearable
            ref="cascader"
            style="width:260px;"
            size="small"
            readonly
            @change="selectQuery"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item prop="posStationType" class='posStationType'>
          <el-select
            v-model="posStationType"
            size="small"
            placeholder="请选择工位和岗位"
            style="width: 100px;"
            @change='selectType'
          >
           <el-option
            v-for="item in posStationList"
            :label="item.label"
            :value="item.value"
            :key="item.value"
            :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="operator">
          <el-select
            v-if='posStationType == 1'
            v-model="queryParmas.operator"
            class="select-value"
            placeholder="请选择工位"
            size="small"
            style="width: 150px;"
            clearable
            @change="queryData"
          >
             <el-option
              v-for="item in stationList"
              :label="item.label"
              :value="item.code"
              :key="item.code"
              >
              </el-option>
          </el-select>

          <el-select
            v-if='posStationType == 2'
            v-model="queryParmas.operator"
            class="select-value"
            placeholder="请选择岗位"
            size="small"
            style="width: 150px;"
            clearable
            @change="queryData"
          >
           <el-option
            v-for="item in postList"
            :label="item.codename"
            :value="item.codevalue"
            :key="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="more">
          <el-button
            type="primary"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['taskMgmt:center:add']"
            >新增</el-button
          >
          <span v-if='activeName != 2'>
            <el-button
              type="primary"
              size="mini"
              :disabled="single != true && single != false"
              @click="handleClose()"
              v-hasPermi="['taskMgmt:center:close']"
              class="mg-l-10"
              >关闭</el-button
            >
          </span>

          <span v-if='activeName == 2'>
            <el-button
              type="primary"
              size="mini"
              :disabled="singleApp != true && singleApp != false"
              @click="handleApprove()"
              v-hasPermi="['taskMgmt:center:examine']"
              class="mg-l-10"
              >审核</el-button
            >
          </span>
          <el-link type="warning" :underline="false" @click="lookMore">更多
            <img src="@/assets/images/workbench/arr-right.png"/>
          </el-link>
        </el-form-item>
      </el-form>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane
          v-for="item in tabList"
          :key='item.name'
          :label="item.label"
          :name="item.name"
        >
          <div class="item" slot="label">
            <img :src="item.path">
            <span class="name">{{item.label}}</span>
            <span class="total-fz" :style="{color:item.num ? item.color : '#606266'}">{{item.num}}</span>
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-table
        ref="Table"
        :data="tableData"
        :key="activeName"
        tooltip-effect="dark"
        show-overflow-tooltip
        style="width: 100%;overflow: auto;"
        height="calc(100% - 40px - 40px - 40px - 50px)"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="任务名称" prop='taskName'>
          <template slot-scope="{ row }">
            <el-button type="text" @click.stop="handleDetail(row)">{{
              row.taskName
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="任务类型" prop="taskType" width="160">
          <template slot-scope="{ row }">
            {{ taskTypeDictObj[row.taskType] }}
          </template>
        </el-table-column>
        <el-table-column label="车间" prop='ownedWorkshopName'></el-table-column>
        <el-table-column label="产线" prop='ownedProductionLineName' min-width="150"></el-table-column>
        <el-table-column label="状态" v-if='activeName == 1' width="80">
          <template slot-scope="{ row }">
            {{ taskStatusDictObj[row.status] }}
          </template>
        </el-table-column>
        <el-table-column label="任务截止时间" prop="actualExecuteEndTime" width="165"></el-table-column>
        <el-table-column label="执行人">
          <template slot-scope="{ row }">
            {{ getOperatorLabel(row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="140">
          <template slot-scope="{row}">
            <!-- 显示规则：状态为待执行或已反驳或执行中,并且没有转办人(即没有被转办过)或转办人是登陆人 -->
            <span v-if='activeName == 1 || activeName == 3'>
              <el-button
                v-hasPermi="['taskMgmt:center:execute']"
                type="text"
                @click.stop="handleExecute(row)"
                >执行</el-button
              >
              <!-- 执行转办，显示规则：状态为待执行或已反驳或执行中，以及该条数据转办人为null或当前登陆人 -->
              <el-button
                v-hasPermi="['taskMgmt:center:transfer']"
                type="text"
                @click.stop="handleTransfer(row)"
                >转办</el-button
              >
              <el-button
                v-hasPermi="['taskMgmt:center:close']"
                type="text"
                @click.stop="handleClose(row)"
                >关闭</el-button
              >
            </span>

            <span v-if='activeName == 2'>
              <el-button
                v-hasPermi="['taskMgmt:center:examine']"
                type="text"
                @click.stop="handleApprove(row)"
                >审核</el-button
              >
              <el-button
                v-hasPermi="['taskMgmt:center:transfer']"
                type="text"
                @click.stop="handleTransfer(row)"
                >转办</el-button
              >
            </span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if='pager.total > 10'
        :total="pager.total"
        :page.sync="pager.pageNum"
        :limit.sync="pager.pageSize"
        @pagination="getData"
      />

      <!-- 新增任务 -->
      <AddDialog
        :visible.sync="addDialog.visible"
        :row="addDialog.row"
        :disabled="addDialog.disabled"
        @refresh="updateData"
      ></AddDialog>

      <!-- 转办 -->
      <TransferDailog
        :visible.sync="transferDailog.visible"
        :row="transferDailog.row"
        @refresh="updateList"
      ></TransferDailog>

      <!-- 任务执行 -->
      <ExecuteDailog
        :visible.sync="executeDailog.visible"
        :row="executeDailog.row"
        @refresh="updateList"
      ></ExecuteDailog>

      <!-- 审核 -->
      <ApproveDailog
        :visible.sync="approveDailog.visible"
        :row="approveDailog.row"
        @refresh="updateList"
      ></ApproveDailog>

      <!-- 批量审核 -->
      <approveTaskBatchDialog
        :visible.sync="approveBatchDailog.visible"
        :rows="approveBatchDailog.row"
        @refresh="updateList"
      ></approveTaskBatchDialog>

      <!-- 关闭 -->
      <CloseDailog
        :visible.sync="closeDailog.visible"
        :rows="closeDailog.row"
        @refresh="updateList"
      ></CloseDailog>

      <!-- 任务详情 -->
      <DetailDialog
        :visible.sync="detailDailog.visible"
        :row="detailDailog.row"
      ></DetailDialog>
    </div>
  </el-dialog>
</template>
<script>
  import AddDialog from "@/views/taskMgmt/center/addDialog";
  import TransferDailog from "@/views/taskMgmt/components/transferTaskDialog";
  import ExecuteDailog from "@/views/taskMgmt/components/executeTaskDialog";
  import ApproveDailog from "@/views/taskMgmt/components/approveTaskDialog";
  import approveTaskBatchDialog from "@/views/taskMgmt/components/approveTaskBatchDialog";
  import CloseDailog from "@/views/taskMgmt/components/closeTaskDialog";
  import DetailDialog from "@/views/taskMgmt/center/detailDialog";
  import { getTaskCenterList } from "@/api/taskMgmt/center";
  import {workHandleList,workApprovalList,workOutList,workReportList} from "@/api/leanTask/report";
  import {taskStatusMap } from "@/views/leanTask/enum";
  import { mapState,mapActions,mapGetters} from "vuex";
export default {
  props:{
    tabName:{
      type:String,
      default:"1"
    },
    visible: {
      type: Boolean,
      default: false
    },
    nomalTotal:{
      type:Array,
      default:()=>[0,0,0,0]
    },
    userInfo:{
      type: Object,
      default: ()=>{}
    }
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val)
      },
      get() {
        return this.visible
      }
    },
    ...mapGetters([
      'treePermitList',
      'name',
      'workStations'
    ]),
    taskTypeDictObj() {
      return this.dictToMap(this.dict.taskType);
    },
    taskStatusDictObj() {
      return this.dictToMap(this.dict.taskStatus);
    },
  },
  dicts: ["taskType","taskStatus","PostManage"],
  data() {
    return {
      tabList:[
        {label:"待处理",name:"1",path:require("@/assets/images/workbench/todo.png"),num:0,color:"#FF9300"},
        {label:"待审核",name:"2",path:require("@/assets/images/workbench/doing.png"),num:0,color:"#2F83FF"},
        {label:"已超时 ",name:"3",path:require("@/assets/images/workbench/warning.png"),num:0,color:"#F54E1E"}
      ],
      tableData:[],
      loading: false,
      activeName:"1",
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      //改善任务列表-待处理
      // 改善任务列表-待审核
      // 待审核上报改善点
      // 改善任务列表-今日超时
      functionMap:{
        "1":"0,2,5",
        "2":"1",
        "3":"3"
      },
      addDialog: {
        visible: false,
        row: null,
        disabled: false,
      },
      transferDailog: {
        visible: false,
        row: null,
      },
      executeDailog: {
        visible: false,
        row: null,
      },
      approveDailog: {
        visible: false,
        row: null,
      },
      approveBatchDailog:{
        visible: false,
        row: null,
      },
      closeDailog: {
        visible: false,
        row: null,
      },

      detailDailog: {
        visible: false,
        row: null,
      },
      queryParmas:{
        ownedFactory: null,
        ownedWorkshop: null,
        ownedProductionLine:null,
        operator:null
      },
      taskStatusMap,
      defaultProps: {
        value: "code",
        label: "label",
        checkStrictly: true,
        emitPath: true,
      },
      stationList:[],
      treeList:[],
      postList:[],
      erpCommonList:[],
      posStationType:"2",
      posStationList:[
        {label:"工位",value:"1",disabled:true},
        {label:"岗位",value:"2",disabled:false}
      ],
      single: null,
      singleApp:null,
      dailogType:"close"
    };
  },

  created() {
  },

  updated() {
    if (this.$refs.Table && this.$refs.Table.doLayout) {
      this.$refs.Table.doLayout();
    }
  },

  methods:{
    dialogClose(){
      this.resetFormData();
    },

    dialogOpen(){
      if(this.nomalTotal?.length){
        this.nomalTotal.forEach((item,index) => {
          if(this.tabList?.length){
            this.tabList[index]["num"] = item;
          }
        })
      }
      this.activeName = this.tabName ? this.tabName : "1";
      if(this.activeName == "2"){
        this.dailogType = "approve";
      }else{
        this.dailogType = "close";
      }
      this.treeList = this.treePermitList.map(factory => {
        return{
          code:factory.code,
          id:factory.id,
          label:factory.label,
          children:factory?.children?.length ? factory.children.map(workshop => {
            return{
              code:workshop.code,
              id:workshop.id,
              label:workshop.label,
              workshopType:workshop.workshopType,
              children:workshop?.children?.length ? workshop.children.map(line => {
                return{
                  code:line.code,
                  id:line.id,
                  label:line.label
                }
              }):[]
            }
          }):[]
        }
      })
      this.treeList = this.getTreeData(this.treeList);
      this.postList = this.userInfo?.postManager?.length ? this.dict.PostManage?.filter(ele => this.userInfo?.postManager?.includes(ele.codevalue)) : this.dict.PostManage
      this.getData()
    },

    getList(status){
      this.loading = true;
      const { pageNum, pageSize } = this.pager;
      let query = {
        ...this.queryParmas,
        queryType:"person"
      }
      if(status == "0,2,5"){
        query = Object.assign(query,{statusList:status.split(",")})
      }
      else{
        query = Object.assign(query,{status:status})
      }
      const param = {
        query: query,
        pageNum,
        pageSize,
      };
      getTaskCenterList(param)
      .then((res) => {
        if(res.code == 200){
          this.tableData = res?.rows || [];
          this.pager.total = res?.total || 0;
          if(status == "0,2,5"){
            this.tabList[0].num = res?.total || 0;
          }
          else if(status == "1"){
            this.tabList[1].num = res?.total || 0;
          }
          else if(status == "3"){
            this.tabList[2].num = res?.total || 0;
          }
          this.loading = false;
        }else{
          this.tableData = [];
          this.pager.total = 0;
          this.pager.pageNum = 1;
          this.loading = false;
        }
      })
      .catch(() => {
        this.tableData = [];
        this.pager.total = 0;
        this.pager.pageNum = 1;
        this.loading = false;
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.addDialog.row = null;
      this.addDialog.visible = true;
      this.addDialog.disabled = false;
    },

    /** 执行/审核转办按钮操作 */
    handleTransfer(row) {
      this.transferDailog.row = row;
      this.transferDailog.visible = true;
    },
    /** 执行按钮操作 */
    handleExecute(row) {
      this.executeDailog.row = row;
      this.executeDailog.visible = true;
    },
    /** 审核按钮操作 */
    handleApprove(row) {
      this.dailogType = "approve";
      let rows = [];
      if (row) {
        rows = [row];
        this.approveDailog.row = row;
        this.approveDailog.visible = true;
      } else {
        rows = this.$refs.Table.selection
        this.approveBatchDailog.row = rows;
        this.approveBatchDailog.visible = true;
      }
    },

    /** 关闭按钮操作 */
    handleClose(row) {
      this.dailogType = "close";
      let rows = [];
      if (row) {
        rows = [row]
      } else {
        rows = this.$refs.Table.selection
      }
      this.closeDailog.row = rows;
      this.closeDailog.visible = true;
    },

    handleSelectionChange(selection) {
      if(this.dailogType == "close"){
        if (selection.length > 1) {
          this.single = false;
        } else if (selection.length == 1) {
          this.single = true;
        } else {
          this.single = null;
        }
      }
      else if(this.dailogType == "approve"){
        if (selection.length > 1) {
          this.singleApp = false;
        } else if (selection.length == 1) {
          this.singleApp = true;
        } else {
          this.singleApp = null;
        }
      }
    },

    handleClick(tab, event) {
      this.loading = true;
      this.tableData = [];
      this.pager.total = 0;
      this.pager.pageNum = 1;
      this.activeName = tab.name;
      this.single = null;
      this.singleApp = null;
      if(this.activeName == "2"){
        this.dailogType = "approve"
      }else{
        this.dailogType = "close"
      }
      this.loading = false;
      this.getData()
    },

    getData(){
      const status = this.functionMap[this.activeName]
      this.getList(status);
    },

    updateList(){
      this.getData();
      this.$emit("updateTotal",this.activeName)
    },

    //新增任务
    updateData(){
      this.tableData = [];
      this.pager.total = 0;
      this.pager.pageNum = 1;
      this.activeName = "1";
      this.dailogType = "close"
      this.updateList()
    },

    handleDetail(row) {
      this.detailDailog.row = row;
      this.detailDailog.visible = true;
    },

    selectQuery(list){
      const item = this.$refs["cascader"].getCheckedNodes();
      this.stationList = [];
      if(item?.length){
        if(item[0].level == 3){//选产线
          this.queryParmas.ownedFactory = item[0]?.pathNodes[0]?.data?.code || null;
          this.queryParmas.ownedWorkshop = item[0]?.pathNodes[1]?.data?.code || null;
          this.queryParmas.ownedProductionLine = item[0]?.data?.code || null;
          const factoryList = this.treePermitList.filter(ele => ele.code === this.queryParmas.ownedFactory)
          const workshopList = factoryList[0].children.filter(item => item.code === this.queryParmas.ownedWorkshop)
          const lineList = workshopList[0].children.filter(item => item.code === this.queryParmas.ownedProductionLine)
          lineList.forEach(item => {
            if(item?.children?.length){//获取工位数据
              this.stationList = this.stationList.concat(item.children)
            }
          })
        }
        else if(item[0].level == 2){//选车间
          this.queryParmas.ownedFactory = item[0]?.pathNodes[0]?.data?.code || null;
          this.queryParmas.ownedWorkshop = item[0]?.data?.code || null;
          this.queryParmas.ownedProductionLine = null;
          let factoryList = this.treePermitList.filter(ele => ele.code === this.queryParmas.ownedFactory);
          const workshopList = factoryList[0].children.filter(item => item.code === this.queryParmas.ownedWorkshop)
          workshopList.forEach(ele => {
            if(ele?.children?.length){//获取产线数据
              ele.children.forEach(item => {
                if(item?.children?.length){//获取工位数据
                  this.stationList = this.stationList.concat(item.children)
                }
              })
            }
            else{
              this.stationList = [];
            }
          })
        }
        else if(item[0].level == 1){//选工厂
          this.queryParmas.ownedFactory = item[0]?.data?.code || null;
          this.queryParmas.ownedWorkshop = null;
          this.queryParmas.ownedProductionLine = null;
          const factoryList = this.treePermitList.filter(ele => ele.code === this.queryParmas.ownedFactory);
          factoryList.forEach(tar => {
            if(tar?.children?.length){//获取车间数据
              tar.children.forEach(ele => {
                if(ele?.children?.length){//获取产线
                  ele.children.forEach(item => {
                    if(item?.children?.length){//获取工位数据
                      this.stationList = this.stationList.concat(item.children)
                    }
                  })
                }
                else{
                  this.stationList = [];
                }
              });
            }
            else{
              this.stationList = [];
            }
          })
        }
        if(this.posStationType == "1"){//如果当前选的工位，则清空工位
          this.queryParmas.operator = null;
        }
        this.posStationList[0].disabled = false;
      }else{
        this.queryParmas.ownedFactory = null;
        this.queryParmas.ownedWorkshop = null;
        this.queryParmas.ownedProductionLine = null;
        this.posStationList[0].disabled = true;
        if(this.posStationType == "1"){//如果当前选的工位，则清空工位
          this.queryParmas.operator = null;
        }
      }
      this.getData()
    },

    //切换工位和岗位，清空工位和岗位的数据
    selectType(){
      this.queryParmas.operator = null;
      this.getData()
    },

    //选择工位和岗位
    queryData(){
      this.getData();
    },

    getOperatorLabel(row) {
      if (row.operatorType == "dept") {
        // 显示部门
        return row.executiveAgencyName || row.executiveAgency;
      }
      let operatorName = row.operatorName;
      return operatorName || "";
    },

    resetFormData(){
      this.tableData = [];
      this.activeName = "1";
      this.dailogType = "close";
      this.queryParmas = {
        ownedFactory: null,
        ownedWorkshop: null,
        ownedProductionLine:null,
        operator:null
      }
      this.posStationType = "2";
      this.erpCommonList = [];
      this.stationList = [];
      this.posStationList = [
        {label:"工位",value:"1",disabled:true},
        {label:"岗位",value:"2",disabled:false}
      ]
    },

    lookMore(){
      this.$router.push({ path: "../taskMgmt/center"}).catch(()=>{});
    }
  },
  components:{
    AddDialog,
    TransferDailog,
    ExecuteDailog,
    ApproveDailog,
    approveTaskBatchDialog,
    CloseDailog,
    DetailDialog
  }
};
</script>
<style lang="scss" scoped>
  .work-abnormal-dialog{
    ::v-deep.el-dialog__body{
      height:calc(100vh - 12rem);
      max-height:calc(100vh - 12rem);
      padding:8px 16px 0 16px;
      .box-card{
        width: 100%;
        height:100%;
        .clearfix{
          color: #F59A23;
          .block-title{
            margin-bottom: 0;
            flex:1
          }
          .block-title{
            margin-bottom: 0;
            .title.line{
              color: #313131;
            }
            .title::before{
              background:#34855B;
            }
          }
          .more{
            margin-bottom: 0.5rem;
            font-size:14px;
            margin-left: 10px;
            .el-link.el-link--warning{
              margin-left: 10px;
              color:#34855B;
              .el-link--inner{
                display:flex;
                align-items: center;
              }
              img{
                width: 16px;
                height: 16px;
              }
            }
          }
          .posStationType{
            margin-right:0
          }
        }
        .el-tabs{
          display: flex;
          align-items: center;
          justify-content: space-between;
          .item {
            display: flex;
            align-items: center;
            img{
              width: 18px;
              height: 18px;
            }
            .name{
              padding:0 6px
            }
            .total-fz{
              font-size:16px;
              line-height: 16px;
            }
          }
          .el-tabs__content{
            margin: 0 0 0.9375rem;
          }
        }
        .pagination-container{
          margin-top: 0;
          margin-bottom: 0;
        }
      }
    }
  }
</style>
